<?php
/*
 * @Descripttion: 检查用户权限
 * @version: v1
 * @Author: Terry
 * @Date: 2021-10-05 16:19:18
 * @LastEditors: Terry
 * @LastEditTime: 2024-12-05 08:41:46
 */
declare (strict_types = 1);

namespace app\middleware;
use think\facade\Db;

class GetAuthWhere
{
    private $request;
    private $authWhere;

    public function handle($request, \Closure $next){
        $this->request = $request;
        //检查用户权限
        $this->authWhere = ['projectCode'=> $this->request->prjCode];
        if(isset($request->module)&&!empty($request->module)) $authWhere = $this->getAuthWhere();
        $request->authWhere  = $this->authWhere;
        return $next($request);
    }

    /**
     * @Descripttion:检查用户可查看/修改的内容 
     * @Author: Terry
     * @Date: 2021-10-13 17:51:41
     * @return  (int) 0=>普通用户 1=>管理员 2=>政府 3=>企业
     */
    private function getAuthWhere($request){
        $func = $this->request->userPortal() ?? 'admin';
        $authWhere = $this->$func();
        return $authWhere;
    }

    /**
     * @Description: 手机端用户账号的数据隔离
     * @Author: Terry
     * @Date: 2024-12-05 08:44:06
     */
    private function user(){
        $request  = $this->request;
        $authWhere =  $this->authWhere;
        $userData = DB::table('certification_projectWorker')->where([
            ['projectCode'=>$request['projectCode']],
            ['wxappUserUuid'=>$request['uuid']],
        ])
        ->order('id desc')
        ->value('corpCode');
        if(!$userData)  $authWhere['projectCode'] = 'failProject';
        return $authWhere;
    }
    /**
     * @Description: pc后台账户的数据隔离条件
     * @Author: Terry
     * @Date: 2024-12-05 08:42:06
     */
    private function admin(){
        $userType = DB::table('platform_userAccount')->where(['userUuid'=>$this->request->uuid])->value('role');
        $authWhere =  $this->authWhere;
        //普通用户或企业帐号查看企业权限
        if(in_array($userType,[0,3])){
            $corptype = DB::table('projectInfo_projectCorpInfo')->where([
                'projectCode'=> $this->request->prjCode,
                'corpCode'=>$this->request->corpCode,
            ])
            ->value('corpType');
            if($corptype != '009') $authWhere['corpCode'] = $this->request->corpCode;
        }
        if($userType == 4) unset($authWhere['corpCode']);

        $method = $this->request->method();
        $data = $this->request->$method();
        //上传的数据有corpCode 说明是添加/修改/带搜索条件的查找
        if(isset($data['corpCode'])&&!empty($data['corpCode'])){
            if(isset($authWhere['corpCode'])){
                //如果是分包单位，无论查找还是搜索只能是自己
                $this->request->authData = ['corpCode'=>$authWhere['corpCode']];
            }else{
                //如果是总包单位，传什么就用什么
                $authWhere['corpCode'] = $data['corpCode'];    
            }
        }
        return $authWhere;
    }

}
